import os
from .settings import PYTHON3_EXE, SANDBOX_PATH, PROBLEMS_PATH
from pybo.settings import VERDICT
import psutil
from subprocess import PIPE
from please_invoker import ExecutionLimits, invoke

def runner(infile, outfile):

  print(infile)
  handler = psutil.Popen([PYTHON3_EXE, os.path.join(os.path.abspath(SANDBOX_PATH), 'test.py'),],
                         stdin = open(infile),
                         stdout = open(os.path.join(os.path.abspath(SANDBOX_PATH), 'outfile'), "w"),
                         stderr = open(os.path.join(os.path.abspath(SANDBOX_PATH), 'error'), "w"),
                        ) 
  limits = ExecutionLimits(real_time=3, memory=256, cpu_time=10) 
                           # cpu_time can be omitted; by default it equals
                           # to real_time.
                           # Warning: don't use this value if you don't
                           # know what is it 

  result = invoke(handler, limits)
  if (result.verdict != "OK"):
      return False
  else:
      return True
    #print(PYTHON3_EXE + ' ' + os.path.abspath(SANDBOX_PATH) + '/test.py <' 
    #             + infile + ' >' + os.path.abspath(SANDBOX_PATH) + '/outfile 2>' +
    #             os.path.abspath(SANDBOX_PATH) + '/error')
    #if os.system(PYTHON3_EXE + ' ' + os.path.abspath(SANDBOX_PATH) + '/test.py <' 
    #             + infile + ' >' + os.path.abspath(SANDBOX_PATH) + '/outfile 2>' +
    #             os.path.abspath(SANDBOX_PATH) + '/error'):
    #    
    #    return False
    #else:
    #    return True

def wordlist_checker(test_data):
    input_content, outfile_content, answer_content = test_data
    return answer_content.strip().split() == outfile_content.strip().split()
           
def run_checker(infile, outfile):
    if not runner(infile, outfile):
       return False
    input_content = open(infile).read()
    answer_content = open(outfile).read()
    outfile_content = open(os.path.abspath(SANDBOX_PATH) + '/outfile').read()
    return wordlist_checker([input_content, outfile_content, answer_content])

def check(problem):
    id = problem.id
    testsdir = os.path.join(PROBLEMS_PATH, str(id), 'tests') 
    testnum = 1
    if not os.path.exists(os.path.join(testsdir, str(testnum))):
        return VERDICT['CF']
    while(os.path.exists(os.path.join(testsdir, str(testnum)))):
        if not run_checker(os.path.join(testsdir, str(testnum)), os.path.join(testsdir, str(testnum)) + '.a'):
            break
        testnum += 1
    else:
        return VERDICT['OK']
    return VERDICT['WA']